<script setup>
import {
    Edit, Delete, Link, Download,
} from '@element-plus/icons-vue'
import axios from 'axios';
import { ref } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import {
    addstaffservice, deletestaffservice, updatestaffservice, getAllservice,
    uploadfileservice, getloadfilenameservice
} from '@/api/companyInfo.js'

//控制添加分类弹窗
const dialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型

//定义变量，控制标题
const title = ref('')
const title2 = ref('上传附件')
//交通路线列表数据模型
const majors = ref([
    { id: 11 }, { id: 23 }
])

const formref = ref(null); //表单校验
//与后端交互的json数据
const pathmodel = ref({
    title: null,
    type: null,
    comment: null
})

const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: '',
    findType: '公司信息'
})
const stafflist = async () => {
    console.log(findmodel.value);
    let result = await getAllservice(findmodel.value);
    console.log("公司信息:" + result.data);
    total.value = result.data.total;
    majors.value = result.data.items;
}
stafflist();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    stafflist();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    stafflist();
}
const cleardata = () => {
    findmodel.value.str = '';
    findmodel.value.pageNum = 1;
    stafflist();
}
//表单校验
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请输入类型', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入内容', trigger: 'blur' },
    ]
}
const add = () => {
    pathmodel.value.title = null
    pathmodel.value.type = null
    pathmodel.value.comment = null
    dialogVisible.value = true
    title.value = '公司信息录入'
}
const addstaff = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let result = await addstaffservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("添加成功")
                dialogVisible.value = false;
                stafflist();
            }
            else ElMessage.error(result.message ? result.message : '添加失败')
        }
    });


}
const updatestaff = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            let result = await updatestaffservice(pathmodel.value);
            if (result.code == 0) {
                ElMessage.success("修改成功")
                dialogVisible.value = false;
                stafflist();
            }
            else {
                ElMessage.error(result.message ? result.message : '修改失败')
            }
        }

    })
}

//删除分类
const del = (row) => {
        ElMessageBox.confirm(
            '你确认删除该条专业信息吗？',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                //用户点击了确认
                let result = await deletestaffservice(row.id)
                if (result.code != 0) ElMessage.error(result.message ? result.message : '删除失败')
                else ElMessage.success('删除成功')
                //再次调用getAllCategory，获取所有文章分类
                stafflist();
            })
            .catch(() => {
                //用户点击了取消
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
    }
    //展示编辑弹窗
    const showDialog = (row) => {
        title.value = '公司信息编辑';
        dialogVisible.value = true;
        //数据拷贝
        pathmodel.value.title = row.title;
        pathmodel.value.type = row.type;
        pathmodel.value.comment = row.comment;
        //扩展i的属性，将来需要传递给后台，完成分类的修改
        pathmodel.value.id = row.id;
    }
    const addorupdate = async () => {
        console.log(title.value);
        if (title.value == '公司信息录入') {
            addstaff();
        }
        else {
            updatestaff();
        }
    }
    const activeTab = ref('first'); // 当前激活的标签页
    const handleTabClick = (tab) => {
        cleardata();
        findmodel.value.findType = tab.props.label;
        stafflist();
    };


    const fileList = ref([]);
    const handleChange = (file, newFileList) => {
        fileList.value = newFileList;
        console.log('Selected files:', fileList.value);
    };
    const elseid = ref();
    const uploadfile = async () => {
        const formData = new FormData();
        fileList.value.forEach(fileItem => {
            formData.append('files', fileItem.raw);
        })
        const formDataArray = Array.from(formData.entries());
        console.log(formDataArray);
        let result = await uploadfileservice(formData, elseid.value)
        if (result.code == 0) {
            ElMessage.success("上传成功")
            dialogVisibleupload.value = false;

        }
        else ElMessage.error(result.message ? result.message : '上传失败')
    };
    const dialogVisibleupload = ref(false);
    const showDialogupload = (row) => {
        fileList.value = [];
        dialogVisibleupload.value = true;
        elseid.value = row.id;
    }
    const downloadfilesingle = async (filename, delay) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                const link = document.createElement('a');
                link.href = `http://localhost:8080/downloadfile/${filename}`;
                link.setAttribute('download', filename);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                resolve();
            }, delay);
        });
    }
    const download = async (row) => {
        let result = await getloadfilenameservice(row.id)
        let filenames = result.data;
        if (filenames.length == 0) {
            ElMessage.error('没有上传附件')
        }
        else {
            for (let i = 0; i < filenames.length; i++) {
                console.log(filenames[i]);
                await downloadfilesingle(filenames[i], i * 1000)
            }
        }
    }

</script>

<template>
    <el-card class="page-container">
        
        <template #header>
            <div class="header">
                <span>公司信息</span>
                <div class="extra">
                    <el-button type="primary" @click="add">新增</el-button>
                </div>
            </div>
        </template>

                <!-- 搜索表单 -->
                <el-form>
                    <el-form-item label="查询条件:">
                        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                        <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                        <el-button @click="cleardata">重置</el-button>

                    </el-form-item>
                </el-form>
                <!-- 文章列表 -->
                <el-table :data="majors" style="width: 100%">
                    <el-table-column label="标题" prop="title"></el-table-column>
                    <el-table-column label="类型" prop="type"></el-table-column>
                    <el-table-column label="内容" prop="comment"></el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="{ row }">
                            <el-button :icon="Download" circle plain type="success" @click="download(row)"></el-button>
                            <el-button :icon="Link" circle plain type="info" @click="showDialogupload(row)"></el-button>
                            <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                            <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="没有数据" />
                    </template>
                </el-table>
                <!-- 分页条 -->
                <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
                    :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background
                    :total="total" @size-change="onSizeChange" @current-change="onCurrentChange"
                    style="margin-top: 20px; justify-content: flex-end" />

    </el-card>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="35%">
        <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="81px" style="padding-right: 30px">
            <el-row gutter="20">
                <el-col :span="12">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="pathmodel.title"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="pathmodel.type" placeholder="请选择类型">
                            <el-option label="新产品资料" value="新产品资料"></el-option>
                            <el-option label="培训资料" value="培训资料"></el-option>
                            <el-option label="公司政策" value="公司政策"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="备注" prop="comment">
                <el-input type="textarea" :rows="4" v-model="pathmodel.comment" style="width: 400px"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addorupdate"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="dialogVisibleupload" :title='title2' width="35%">
        <el-upload action="none" class="upload-demo" drag :auto-upload="false" :http-request="httpRequest"
            :file-list="fileList" @change="handleChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisibleupload = false">取消</el-button>
                <el-button type="primary" @click="uploadfile"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>